<template>
  <div class="dia">
    <!--模态框-->
    <el-dialog
      class="remarks"
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
      width="65%"
      @close="handleDialogClose"
    >
      <template slot="title">
        <div class="titleZise">
          <svg-icon icon-class="flow-add" />
          <span>选择工作流上传</span>
        </div>
      </template>
      <div v-loading="addLoading">
        <el-form
          ref="dataForm"
          :inline="true"
          :model="form"
          :rules="rules"
          label-width="30%"
          class="demo-ruleForm"
        >
          <el-divider><span style="color: #b5b4b4">编码信息</span></el-divider>
          <el-form-item
            :label="tempDesc.organization"
            prop="organization"
            class="formItem normalInput"
          >
            <el-select v-model="form.organization" placeholder="请选择">
              <el-option
                v-for="item in orgs"
                :key="item.itemText"
                :label="item.itemValue"
                :value="item.itemText"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            :label="tempDesc.modelNum"
            prop="modelNum"
            class="formItem normalInput"
          >
            <el-input v-model="form.modelNum"></el-input>
          </el-form-item>
          <el-form-item
            :label="tempDesc.speciality"
            prop="speciality"
            class="formItem normalInput"
          >
            <el-select v-model="form.speciality" placeholder="请选择">
              <el-option
                v-for="item in spes"
                :key="item.itemText"
                :label="item.itemValue"
                :value="item.itemText"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            :label="tempDesc.modelNumPart"
            prop="modelNumPart"
            class="formItem normalInput"
          >
            <el-input v-model="form.modelNumPart"></el-input>
          </el-form-item>
          <el-form-item
            :label="tempDesc.versionNum"
            prop="versionNum"
            class="formItem normalInput"
          >
            <el-input v-model="form.versionNum"></el-input>
          </el-form-item>
          <el-form-item
            :label="tempDesc.freeNum"
            prop="freeNum"
            class="formItem normalInput"
          >
            <el-input v-model="form.freeNum"></el-input>
          </el-form-item>
          <el-form-item align="right" style="width: 100%">
            <el-button
              icon="el-icon-coordinate"
              type="primary"
              @click="create_pre_id"
            >
              生成工作流编号
            </el-button>
          </el-form-item>

          <el-divider>
            <span style="color: #b5b4b4">上传工作流</span>
          </el-divider>
          <el-form-item
            label-width="15%"
            :label="tempDesc.preId"
            prop="preId"
            class="longInput"
          >
            <el-input v-model="form.preId" disabled></el-input>
          </el-form-item>

          <el-form-item
            :label="tempDesc.wfName"
            prop="wfName"
            class="formItem normalInput"
          >
            <el-input
              v-model="form.wfName"
              placeholder="请输入工作流名称"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="描述"
            prop="description"
            class="formItem normalInput"
          >
            <el-input
              v-model="form.description"
              placeholder="请输入工作流描述信息"
            ></el-input>
          </el-form-item>
          <el-divider><span style="color: #b5b4b4">上传文件</span></el-divider>
          <el-form-item prop="file" class="formItem normalInput">
            <template slot="label">
              <span style="color: red">*</span>
              上传文件
            </template>
            <el-upload
              ref="upload"
              :action="url.upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :file-list="file"
              multiple
              :headers="headers"
              :on-success="handleSuccess"
              name="file"
              :on-change="handleChange"
            >
              <el-button
                slot="trigger"
                icon="el-icon-upload"
                plain
                size="small"
                type="primary"
              >
                选取文件
              </el-button>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button v-waves :disabled="addLoading" @click="closeDialog">
          取消
        </el-button>
        <el-button
          v-waves
          :disabled="addLoading"
          type="primary"
          @click="succeedClose"
        >
          保存
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import { getToken } from '@/utils/auth'
  import { getAction, postAction } from '@/api/action'
  //常量title
  const tempDesc = {
    speciality: '专业',
    dataType: '数据类型',
    organization: '组织',
    modelNum: '型号',
    modelNumPart: '部件',
    versionNum: '版本编号',
    freeNum: '自由编号',
    preId: '工作流编号',
    name: '名称',
    wfName: '工作流名称',
  }
  export default {
    name: 'UploadFileModal',
    props: {
      dialogVisible: {
        type: Boolean,
        defaultValue: false,
      },
      stageType: {
        type: Number,
        required: true,
      },
    },
    data() {
      //自定义校验规则
      var maxSize = (rule, value, callback) => {
        if (!value && rule.field != 'freeNum') {
          return callback(new Error('不能为空'))
        }
        let maxLength = 6 //最大位数,默认6位
        if (rule.field == 'organization') {
          maxLength = 5
        }
        if (rule.field == 'freeNum') {
          maxLength = 30
          if ((value = '')) {
            this.modelForm[rule.field] = ''
          }
        }
        if (value.length > maxLength) {
          return callback(new Error('不能大于' + maxLength + '位数'))
        } else {
          //不足6位的填充0到6位
          // let fill = '';
          // for (let i =0 ; i < maxLength - value.length ; i++){
          //   fill += "0";
          // }
          // this.form[rule.field] = fill + this.form[rule.field];
        }
        callback()
      }
      //不能为空
      var blankSpace = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('不能为空'))
        }
        callback()
      }
      //文件是否上传成功
      var isupload = (rule, value, callback) => {
        if (this.valutData.id == undefined) {
          return callback(new Error('不能为空'))
        }
        callback()
      }
      return {
        tempDesc: tempDesc,
        addLoading: false,
        url: {
          upload: 'http://localhost:18086/presoftasim/common/upload',
          save: '/presoftasim/wf/workflow/save',
          createPreId: '/presoftasim/wf/workflow/createPreId',
          getModelFromSelects: '/presoftasim/wf/workflow/getModelFromSelects',
        },
        // fileList: [
        //   {
        //     key: 'aaaa',
        //     fileName: 'project_attach_1591586771855.txt',
        //   },
        // ],
        headers: {
          contentType: 'multipart/form-data; charset=utf-8',
          'presoft-Token': getToken(),
        },
        form: {
          description: undefined,
          dataType: undefined,
          organization: undefined,
          modelNum: undefined,
          modelNumPart: undefined,
          versionNum: undefined,
          freeNum: undefined,
          createrPreId: undefined,
          preId: undefined,
          speciality: undefined,
          createTime6: undefined,
          specialityName: undefined,
          organizationName: undefined,
          name: undefined,
          wfName: undefined,
          createUser: undefined,
          stageType: undefined,
        },
        orgs: [], //modelForm中organization组织选项列表
        spes: [], //modelForm中speciality专业选项列表
        rules: {
          organization: [
            { validator: maxSize, trigger: 'change' },
            { required: true, trigger: 'blur' },
          ],
          modelNum: [
            { validator: maxSize, trigger: 'blur' },
            { required: true, trigger: 'blur' },
          ],
          speciality: [
            { validator: maxSize, trigger: 'change' },
            { required: true, trigger: 'blur' },
          ],
          modelNumPart: [
            { validator: maxSize, trigger: 'blur' },
            { required: true, trigger: 'blur' },
          ],
          versionNum: [
            { validator: maxSize, trigger: 'blur' },
            { required: true, trigger: 'blur' },
          ],
          freeNum: [{ validator: maxSize, trigger: 'blur' }],
          wfName: [
            { validator: blankSpace, trigger: 'blur' },
            { required: true, trigger: 'blur' },
          ],
          preId: [
            { validator: blankSpace, trigger: 'change' },
            { required: true, trigger: 'blur' },
          ],
          file: [{ validator: isupload, trigger: 'blur' }],
        },
        valutData: {},
        file: [],
        titleMap: {
          create: '创建用户',
          update: '编辑用户',
        },
      }
    },
    created() {
      this.getModelFromSelects()
    },
    methods: {
      handleSuccess(res) {
        this.valutData = res.data
        this.$refs['dataForm'].validateField(['file'], (errmessage) => {})
      },
      handleRemove(file, fileList) {
        console.log(file, fileList)
      },
      handlePreview(file) {
        // console.log(file);
      },
      handleExceed(files, fileList) {
        this.$message.warning(
          `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length} 个文件`
        )
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${file.name}？`)
      },
      closeDialog() {
        //this.show = false;  //这行去掉 不能直接改变props中参数的值
        this.addLoading = false
        // this.fileList = []
        this.$refs['dataForm'].resetFields()
        this.$emit('closeDialog', false) //通知父组件改变。
        this.$refs['upload'].clearFiles() //清空上传列表
        this.valutData = {}
      },
      succeedClose() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.addLoading = true
            this.form.valutId = this.valutData.id
            this.form.stageType = this.stageType
            let param = Object.assign({}, this.form, this.valutData)
            postAction(this.url.save, param).then((response) => {
              this.$emit('closeDialog', true) //通知父组件改变。
              this.addLoading = true
              if (response.code === 200) {
                this.$message.success(response.message)
              } else {
                this.$message({
                  duration: 8000,
                  message: response.message,
                  type: 'error',
                })
              }
              this.file = []
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      // 监听dialog关闭时的处理事件
      handleDialogClose() {
        this.closeDialog()
      },
      //生成72位编码
      create_pre_id: function () {
        //校验表单输入书否符合要求，若全部符合才向服务端发起请求
        let handle = true
        this.$refs['dataForm'].validateField(
          [
            'organization',
            'modelNum',
            'speciality',
            'modelNumPart',
            'versionNum',
            'freeNum',
          ],
          (errmessage) => {
            if (errmessage != '') {
              handle = false
              return console.log(errmessage)
            }
          }
        )
        if (handle) {
          this.form.createUser = this.$store.state.user.id
          postAction(this.url.createPreId, this.form)
            .then((response) => {
              if (response.code === 200) {
                this.form.preId = response.data.preId
                this.form.createrPreId = response.data.createrPreId
                this.form.createTime6 = response.data.createTime6
                this.form.dataType = response.data.dataType
                if (this.form.freeNum == '' || this.form.freeNum == undefined) {
                  this.form.freeNum = response.data.freeNum
                }
                this.getValue()
              } else {
                this.submitFail(response.message)
              }
            })
            .catch((err) => {
              console.log(err)
            })
        }
      },
      //获取组织、专业名称
      getValue: function () {
        for (let i in this.orgs) {
          if (this.form.organization == this.orgs[i].itemText) {
            this.form.organizationName = this.orgs[i].itemValue
          }
        }
        for (let i in this.spes) {
          if (this.form.speciality == this.spes[i].itemText) {
            this.form.specialityName = this.spes[i].itemValue
          }
        }
      },

      //获取组织、专业选择列表
      getModelFromSelects: function () {
        getAction(this.url.getModelFromSelects, this.form)
          .then((response) => {
            if (response.code === 200) {
              this.orgs = response.data.organization
              this.spes = response.data.speciality
            } else {
              this.submitFail(response.message)
            }
          })
          .catch((err) => {
            console.log(err)
          })
      },
      // 文件列表发生变化时触发校验
      fileChange: function () {
        // this.$refs["dataForm"].validateField(['file'], (errmessage) => {
        // });
      },
      //上传文件发生改变
      handleChange: function () {
        this.fileChange()
      },
    },
  }
</script>
<style lang="scss">
  .formItem {
    width: 45%;
  }
  .normalInput .el-form-item__content {
    width: 70%;
    margin: 0px;
  }
  .longInput .el-form-item__content {
    width: 85%;
  }
  .el-form-item {
    margin-right: 0px;
  }
  .longInput {
    width: 90%;
  }
  .el-select {
    width: 100%;
    margin: 0px;
  }
</style>
